;
(function (w) {
  var app = new Vue({
    el: '#customerManagement',
    data: {
      listMenu: [
      {
        name: '潜在客户',
        code: 'PO',
        num: 0
      },
      {
        name: '意向客户',
        code: 'YX',
        num: 0
      },
      {
        name: '成交客户',
        code: 'CJ',
        num: 0
      },
{
        name: '重点客户',
        code: 'ZD',
        num: 0
      },
      {
        name: '流失客户',
        code: 'LS',
        num: 0
      },
			{
			  name: '解约客户',
			  code: 'JY',
			  num: 0
			}
      ],
      blackStatus: '#',
      blackStatusNum: 0,
      selectedListMenuCode: [],
      keyWord: null,
      sortName: null,
      sortType: 'ASC',
      rperson: {
        name: null,
        list: [],
        id: null
      }, // 对接人
      rpersonKeyword: null,
      totalPage: 0,
      totalCount: 0,
      currentPage: 1,
      limit: ['10'],
      totalCount: 0,
      pageCounts: [{ name: '10', code: '10' }, { name: '15', code: '15' }, { name: '20', code: '20' }],
      tableType: 'scroll',
      isScroll: false,
      tbTitleWidth: {
        width: 990 + 'px'
      },
      tbTotalWidth: {
        width: 957 + 'px'
      },
      customerType: [{
        'name': '全部',
        'code': '#'
      }, {
        'name': '公司',
        'code': 'QY'
      }, {
        'name': '个人',
        'code': 'PE'
      }],
      selectedProject:[], //已选的项目
      projectList:[],//所有项目
      selectedCustomerType: [],
      industryType: [],
      selectedIndustryType: [],
      channelType: [], //渠道分类
      selectedChannelType: [],
      channelName: [], //渠道名称
      selectedChannelName: [],
      blackData: [],
      selectedBlackType: [],
      personList: [], //商机来源
      listData: [],
      countInfoData: [],
      isShowPersonLayer: false,
      isShowSelector: false,
      isShowOperationBar: true,
      isExtenseFlag: false,
      quanxian: JSON.parse(localStorage.getItem('permissions')),
      configType: 'WZ', //默认完整WZ     JD简单，WZ完整，自定义配置PZ
      module: '#',
      headArr: [],
      sortTableTitle: [],
      isScroll: false,
      isShowTableLayer: false,
      dateTimeUpdate: [],
      isActiveCode: '#',
      tbTitleWidth: {},
      listObj: {},
      columns: '',
      orders: '',
			//start
			importFlag: false,
			through: false,
			notThrough: false,
			detection: false, //检测
			detectionBtn: true,
			isShowDownload: false,
      is500: false,
      

      repeatSearchFlag: false,
      repeatXSlist: [],
      selectedXS: [],
      selectedCopyXS: [],
      repeatXSflag:false,

      loadingflag:true

    },
    filters: {
      formatYYYYMMddHHmmss(item) {
        if (!item) return '--'
        return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm:ss')
      },
      formatUndefined: function (item) {
        if (!item) return '--'
        if (typeof item == 'number') {
          if (!isNaN(item) && item.toString().length == 13) {
            return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
          };
        }
        return item
      },
    },
    methods: {
      repeatXSfun(){
        this.currentPage = 1;
        this.repeatXSflag = true
        this.searchData()
      },
      resetRepeatXS(){
        this.currentPage = 1;
        this.repeatXSflag = false
        this.searchData()
      },
      sureAddRepeatFun() {
        this.selectedCopyXS = JSON.parse(JSON.stringify(this.selectedXS))
        this.repeatSearchFlag = false
        hlhttp.put({
          url: 'customer/repeat_rules',
          data: {
            rules: this.selectedXS.length ? this.selectedXS + '' : '#'
          },
          success: data => {
            this.getSelectedXSdict()
          }
        })
      },
      addRepeatSearchFun() {
        this.repeatSearchFlag = true
        this.selectedXS = JSON.parse(JSON.stringify(this.selectedCopyXS))
      },
      // 获取重复线索字典
      getBusinessDict() {
        hlhttp.get({
          url: 'configure/dict',
          data: { 'module_code': 'ZHSH', 'config_name': 'ZS_REPEAT_RULE' },
          success: data => {
            data.map(item => {
              item.name = item.dictName
              item.code = item.dictCode
            })
            this.repeatXSlist = data
          }
        })
      },
      // 获取已选线索
      getSelectedXSdict() {
        hlhttp.get({
          url: 'customer/repeat_rules',
          success: data => {
            this.selectedCopyXS = data
          }
        })
      },
      selectedXSfun(code) {
        let index = this.selectedXS.indexOf(code)
        if (index == -1) {
          this.selectedXS.push(code)
        } else {
          this.selectedXS.splice(index, 1)
        }
      },




      //获取项目
			getprojectData () {
			  hlhttp.get({
			    url: 'user/projects',
			    success: (res) => {
						res = hlArrayUtil.removeRepeat(res, 'projectId')
						this.projectList = hlArrayUtil.replaceData(res, [{key: 'projectName', rKey: 'name'}, {key: 'projectId', rKey: 'code'}]);
			    }
			  })
			},
			//导入
			importExcl() {
			  this.importFlag = true;
			},
			//关闭
			importExclClose() {
			  this.importFlag = false;
			  this.detection = false;
			  this.notThrough = false;
			  this.detectionBtn = true;
			  this.through = false;
			  this.srcUrl = '';
			  $('.filename-i').val('')
			},
			//导出
			customer_export () {
				hlhttp.get({
				  baseUrl: exclUrl,
				  url: 'resource/customer/_export',				  
				  success: (data) => {
				    console.log(data)
						window.open(data.url)
				  }
				})
			},
			//上传模板
			downloadxslc() {
			  $('.upload-filess').trigger('click')
			  this.detection = false;
			  this.notThrough = false;
			  this.detectionBtn = true;
			  this.through = false;
			  this.srcUrl = '';
			  $('.filename-i').val('')
			},
			//获取客户导入模板
			getExcl () {
				hlhttp.get({
				  baseUrl: exclUrl,
				  url: 'resource/customer_upload_template_excel',				  
				  success: (data) => {
				    console.log(data)
						window.open(data.url)
				  }
				})
			},
			//检测
			detectionXslx() {
			  this.detection = true;
			  this.detectionBtn = false;
			  if (!this.srcUrl) {					
					return
				};
			
			  hlhttp.put({
			    baseUrl: exclUrl,
			    url: 'resource/customer_upload_data/_check',
			    data: {
			      file_name: this.srcUrl
			    },
			    success: res => {
			      if (res.code == 200) {
			        this.detection = false;
			        this.notThrough = false;
			        this.detectionBtn = false;
			        this.through = true;
			        this.isShowDownload = true;
			        this.is500 = false;
			      }
			      if (res.code == 400) {
			        this.detection = false;
			        this.notThrough = true;
			        this.detectionBtn = false;
			        this.is500 = false;
			        this.through = false;
			        this.isShowDownload = true;
			        this.srcUrl = res.url
			      }
			      if (res.code == 500) {
			        this.is500 = true;
			        this.detection = false;
			        this.notThrough = false;
			        this.detectionBtn = false;
			        this.through = true;
			        this.srcUrl = res.url;
			        this.isShowDownload = true;
			      }
			    },
			    error: res => {
			      hl.toast('请使用标准模板上传！')
			      this.detection = false;
			      this.notThrough = true;
			      this.detectionBtn = false;
			      this.isShowDownload = false;
			      this.through = false;
			    }
			  })
			},
			//submit xslc
			submibXslc() {
			  hlhttp.post({
			    baseUrl: exclUrl,
			    url: 'resource/customer_upload_data',
			    data: {
			      file_name: this.srcUrl.indexOf('/') > -1 ? this.srcUrl.substr(this.srcUrl.lastIndexOf('/') + 1) : this.srcUrl,
			      is_myself: 'N'
			    },
			    success: () => {
			      hl.toast('上传成功')
			      this.searchData()
			      this.importExclClose()
			    }
			  })
			},
			//end
      selectMenuList() {
        this.currentPage = 1
        this.searchData()
      },
      goTodetail(id) {
        hlUrlUtil.goTo('customerDetails', { 'id': id, 'ddtab': true, 'page': 'customerManagement' }, true)
      },
      resetTabbar() {
        this.selectedListMenuCode = []
        this.currentPage = 1
        this.searchData()
      },
      openSearch: function () {
        if (this.isExtenseFlag == true) {
          this.isExtenseFlag = false;
          return false;
        }
        if (this.isExtenseFlag == false) {
          this.isExtenseFlag = true;
          return false;
        }
      },
      searchData() {
        var self = this;
        this.loadingflag = true
        var submitData = {
          'keyword': self.keyWord || '#',
          'customer_type': self.selectedCustomerType.length ? self.selectedCustomerType + '' : '#',
          'industry_code': self.selectedIndustryType.length ? self.selectedIndustryType + '' : '#',
          'rperson_id': self.rperson.id || '#',
          'channel_category_code': self.selectedChannelType.length ? self.selectedChannelType[0] : '#',
          'channel_name_code': self.selectedChannelName.length ? self.selectedChannelName[0] : '#',
          'customer_state': self.selectedListMenuCode.length ? self.selectedListMenuCode.join(',') : '#',
          'black_status': self.selectedBlackType.length ? self.selectedBlackType[0] : '#',
          'limit': self.limit[0],
          'page': self.currentPage,
          'columns': self.columns || '#',
          'orders': self.orders || '#',
          'project_id':self.selectedProject.length?self.selectedProject + '' : '#'
        }
        if (this.repeatXSflag) {
          submitData.repeat_flag = 'Y'
          submitData.repeat_rules = this.selectedCopyXS + ''
        }

        hlhttp.get({
          url: 'customer_manager_search',
          data: submitData,
          success: function (data) {
            self.listObj = data
            self.listData = data.myCustomers;
            self.totalCount = data.totalCount;
            self.totalPage = data.totalPage;
            self.countInfoData = data.countInfo;

            self.blackStatusNum = data.countInfo.BC;
            self.listMenu.forEach(el => {
              if (el.code == 'PO') el['num'] = data.countInfo.PO;
              if (el.code == 'YX') el['num'] = data.countInfo.YX;
              if (el.code == 'LS') el['num'] = data.countInfo.LS;
              if (el.code == 'CJ') el['num'] = data.countInfo.CJ;
              if (el.code == 'JY') el['num'] = data.countInfo.JY;
              if (el.code == 'ZD') el['num'] = data.countInfo.ZD || 0;
            })
            self.loadingflag = false
          }
        })
      },
      //查询
      search() {
        this.currentPage = 1;
        this.limit = ['10'];
        this.searchData()
      },
      reset() {
        this.keyWord = null;
        this.selectedCustomerType = []
        this.selectedIndustryType = []
        this.rpersonKeyword = ''
        this.selectedChannelType = []
        this.selectedChannelName = []
        this.selectedBlackType = ['#']
        this.selectedProject = []
        this.columns = '',
          this.orders = '',
          this.isActiveCode = '#';
        this.rperson = {
          name: null,
          list: [],
          id: null
        };
        this.search()
      },
      // 获取对接人人员列表
      getRpersonData() {
        var self = this;
        hlhttp.get({
          url: 'tenants/users/_search',
          data: {
            'keyword': self.rpersonKeyword || '#',
            'first_order': 'Y'
          },
          success: function (data) {
            self.rperson.list = data;
            // 自动匹配  当输入的名字跟下拉列表中名字匹配时  则存储ID
            data.forEach(el => {
              if (el.name == self.rpersonKeyword) {
                self.rperson.name = self.rpersonKeyword;
                self.rperson.id = el.id;
              }
            })
          }
        })
      },
      // 设置对接人name，获取id
      setRperson(name, id) {
        this.rperson = {
          name: name,
          list: [],
          id: id
        }
        this.rpersonKeyword = name
      },
      hideRpersonList() {
        this.rperson.list = [];
      },
      // 获取产业
      getIndustryType() {
        hlhttp.get({
          url: 'configure/industry/dict',
          success: data => {
            data.unshift({
              'dictName': '全部',
              'dictCode': '#'
            })
            this.industryType = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }]);
          }
        })
      },
      // 渠道分类
      getChannelType() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_CHANNEL_CATE'
          },
          success: data => {
            this.channelType = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }]);
          }
        })

      },
      selectChannelType() {
        this.selectedChannelName = []
        this.getChannelName()
      },
      // 获取渠道名称
      getChannelName() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_CHANNEL_NAME',
            parent_dict_code: this.selectedChannelType[0]
          },
          success: data => {
            this.channelName = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }]);
          }
        })
      },

      //线索来源
      getBlack() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_BLAKLIST_TYPE'
          },
          success: data => {
            data.unshift({
              'dictName': '全部',
              'dictCode': '#'
            })
            this.blackData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }]);
            this.selectedBlackType = [data[0]['dictCode']]
          }
        })
      },

      // 获取用户工作组组员
      getPerson() {
        hlhttp.get({
          url: 'data_group/users/_search',
          data: {
            keyword: '#'
          },
          success: data => {
            this.personList = data;
          }
        })
      },
      selectPerNum(arr) {
        this.limit = [arr[0].code]
        this.currentPage = 1
        this.searchData()
      },
      sortByRecordTime() {
        if (this.sortType == 'ASC') {
          this.sortType = 'DESC'
        } else {
          this.sortType = 'ASC'
        }
        this.searchData()
      },
      selectDispatchItem(isChecked, i) {
        if (isChecked == 'Y') this.$set(this.listData[i], 'isChecked', 'N');
        if (isChecked == 'N') this.$set(this.listData[i], 'isChecked', 'Y');

        let isAllSelected = true;
        this.listData.forEach(el => {
          if (el.isChecked == 'N') isAllSelected = false
        })
        if (isAllSelected) {
          this.isAllSelected = true;
        } else {
          this.isAllSelected = false;
        }
      },
      closePersonLayer() {
        this.isShowPersonLayer = false;
      },
      confirmDispatchSingleItem() {
        hlhttp.put({
          url: 'customer/biz_oppt_assign',
          data: {
            sj_ids: this.selectedSingleItem.sjId,
            assignee_id: this.selectedSingleItem.id,
            assignee_name: this.selectedSingleItem.name
          },
          success: data => {
            hl.toast('分派成功')
            this.isShowPersonLayer = false;
            this.isShowOperationBar = true;
            this.search()
          }
        })
      },
      dispatchValidate() {
        this.listData.forEach(el => {
          if (el.isChecked == 'Y') {
            if (this.selectedMulItem.sjIds.indexOf(el.sjId) == -1) this.selectedMulItem.sjIds.push(el.sjId)
          }
        })
        if (!this.selectedMulItem.id) {
          hl.toast('请选择分派人')
          return false
        }
        if (!this.selectedMulItem.sjIds) {
          hl.toast('请选择分派项目')
          return false
        }
        return true
      },
      confirmDispatchMulItem() {
        var valid = this.dispatchValidate()
        if (valid) {
          hlhttp.put({
            url: 'customer/biz_oppt_assign',
            data: {
              sj_ids: this.selectedMulItem.sjIds.join(','),
              assignee_id: this.selectedMulItem.id,
              assignee_name: this.selectedMulItem.name
            },
            success: data => {
              hl.toast('分派成功')
              this.isShowPersonLayer = false;
              this.isShowOperationBar = true;
              this.search()
            }
          })
        }

      },
      dispatchBusiness(id) {
        this.selectedSingleItem.sjId = id;
        this.isShowPersonLayer = true;
      },
      showScroll() {
        this.isScroll = true;
      },
      hideScroll() {
        this.isScroll = false;
      },
      goToAddCustomer() {
        hlUrlUtil.goTo('createCm', {
          ddtab: true
        }, true)
        window.sessionStorage.removeItem('RENT_BUSINESS_CUSTOMER')
      },
      sortBySTTime(item) {
        this.isActiveCode = item.value;
        this.orders = item.orders
        this.columns = item.columns
        this.searchData()
      },
      //获取自定义表头配置状态
      configTypeDt() {
        hlhttp.get({
          url: 'configure/customize_column_header/type',
          data: { module: 'ZHSH_KHGL' },
          success: (data) => {
            this.configType = data.configType;
            this.customizeHeaderDt()
          }
        })
      },
      //获取自定义表头配置信息
      customizeHeaderDt() {
        hlhttp.get({
          url: 'configure/customize_column_header',
          data: { module: 'ZHSH_KHGL' },
          success: (data) => {
            data.customConfigList.map(item => {
              item.seq = Number(item.seq)
              item.customSeq = Number(item.customSeq)
              item.isActive = 'N'
              if (item.orderFlag == 'Y') {
                this.dateTimeUpdate.push(item.value)
              }
            })
            if (this.configType == 'JD' || this.configType == 'WZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('seq'))
            }
            if (this.configType == 'PZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('customSeq'))
            }
            this.headArr = JSON.parse(JSON.stringify(data.customConfigList));
            this.sortTableTitle = JSON.parse(JSON.stringify(data.customConfigList));
            this.tbTitleWidthCalculation()
          }
        })
      },
      //宽度计算
      tbTitleWidthCalculation() {
        let w = 0, flag = false;
        this.headArr.map(item => {
          if (item.name == '序') {
            flag = true;
          }
        })
        w = this.headArr.length * 120 - 80;
        this.tbTitleWidth = { width: w + 'px' }
      },
      //弹窗显示
      showTableLayer() {
        this.isShowTableLayer = true;
      },
      //关闭自定义表头弹窗
      closeTableLayer() {
        this.isShowTableLayer = false;
      },
      //简单完整配置切换
      selectTableType(obj) {
        this.configType = obj.code;
        this.updateConfigType()
      },
      //更新自定义表头配置状态
      updateConfigType() {
        hlhttp.put({
          url: 'configure/customize_column_header/type',
          data: { module: 'ZHSH_KHGL', config_type: this.configType },
          success: () => {
            this.configTypeDt()
          }
        })
      },
      // 确定提交自定义表格
      confirmSubmitTable(data) {
        let dataArr = [];
        data.map((item, index) => {
          dataArr.push({
            "base_flag": item.baseFlag,
            "seq": item.seq,
            "custom_show_flag": item.customShowFlag,
            "custom_seq": item.newIndex,
            "custom_display_name": item.customDisplayName,
            "union_table_part": item.unionTablePart,
            "dict_code": item.dictCode,
            "config_type": item.configType,
            "name": item.name,
            "value": item.value,
            "style_width": item.styleWidth,
            "flex": item.flex,
            "order_flag": item.orderFlag,
            "order_name": item.orderName
          })
        })
        hlhttp.put({
          url: 'configure/customize_column_header',
          data: {
            module: 'ZHSH_KHGL',
            custom_config: JSON.stringify(dataArr)
          },
          success: (data) => {
            hl.toast('操作成功')
            this.closeTableLayer()
            this.updateConfigType()
          }
        })
      },
    },
    mounted: function () {
      hlSelectUi()
      this.configTypeDt()
      this.getChannelType()
      this.getIndustryType()
      this.search()

      this.getBlack()
      this.getPerson()
      this.getprojectData()

      
      this.getBusinessDict()
      this.getSelectedXSdict()
			
			
			fileUpload('.upload-filess', uploadUrl, (src) => {
			  if (src.json == undefined) return;
			  if (!(src.json.name.indexOf('xls') > -1)) {
			    hl.toast('请上传正确的模板')
			    return
			  }
			  if (!(src.json.name.indexOf('xlsx') > -1)) {
			    hl.toast('请上传正确的模板')
			    return
			  }
			  this.srcUrl = src.json.url.substr(src.json.url.lastIndexOf('/') + 1);
			  $('.filename-i').val(src.json.name)
			})

    }
  })
}(window))
